package com.mediacloud.app.newsmodule.fragment.audio.vod;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;

import android.view.View;
import android.widget.TextView;

import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.ImageButtonX;
import com.mediacloud.app.assembly.views.NetImageViewX;
import com.mediacloud.app.cloud.ijkplayersdk.untils.Tools;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.AudioVodBroadcast;
import com.mediacloud.app.newsmodule.service.AudioConst;
import com.mediacloud.app.newsmodule.service.AudioLivePlayService;
import com.mediacloud.app.newsmodule.service.AudioVodPlayService;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mediacloud.app on 2017/2/16.
 */

public class NewsDetailAudioPlayerFragment extends BaseFragment implements View.OnClickListener, AudioVodBroadcast.AudioVodBroad {

    protected boolean isFirst = true;
    protected boolean isAutoPlay = true;
    protected boolean isPlay = false;
    protected boolean isComplete = false;
    protected boolean getDeatils = false;
    protected String url;
    protected TextView play_progress;
    protected ArticleItem articleItem;
    protected ImageButtonX audio_play;
    protected NetImageViewX audio_logo;
    protected Map<String, String> lineMap = new LinkedHashMap<String, String>();
    protected AudioVodBroadcast broadcast;
    protected int lineIndex = -1;
    protected List<String> streamLabelList = new ArrayList<String>();
    protected TextView audio_title;

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_imgtxt_news_audioplayer;
    }

    @Override
    public void initView() {
        Bundle bundle = getArguments();
        articleItem = bundle.getParcelable("data");
        AppConfig appConfig = new AppConfig(getContext());
        isAutoPlay = false;//appConfig.isAutoplay();
        audio_logo = Utility.findViewById(mRootView, R.id.audio_logo);
        audio_play = Utility.findViewById(mRootView, R.id.audio_p);
        play_progress = Utility.findViewById(mRootView, R.id.play_progress);
        audio_title = Utility.findViewById(mRootView, R.id.audio_title);
        audio_logo.load(articleItem.getAudio_logo());
//        audio_logo.load("http://a.pic1.ajkimg.com/display/hj/d4ddc700562afe6b42da4a543999640a/600x450.jpg");
        audio_title.setText(articleItem.getAudio_title());
        audio_title.setSelected(true);
        KillMusicUtils.stopAPS(requireContext());
        audio_play.setClickable(false);
        audio_play.setOnClickListener(this);
        initBroad();
        sendPlayCMD();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    protected void initBroad() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(AudioVodBroadcast.Audio_UpdateTime);
        filter.addAction(AudioVodBroadcast.AudioComplete);
        broadcast = new AudioVodBroadcast();
        getActivity().registerReceiver(broadcast, filter);
        broadcast.audioLiveBroadHanlder = this;

        Intent intent = new Intent();
        intent.putExtra(AudioConst.Action, AudioConst.CREATE_ACTIVITY);
        intent.setClass(getContext(), AudioVodPlayService.class);
        startService(intent);
    }

    @Override
    public void onDetach() {

        KillMusicUtils.stopAPS(requireContext());
        if (broadcast != null){
            getContext().unregisterReceiver(broadcast);
            Intent intent = new Intent();
            intent.putExtra(AudioConst.Action, AudioConst.DESTROY_ACTIVITY);
            intent.setClass(getContext(), AudioVodPlayService.class);
            startService(intent);
        }
        super.onDetach();
    }


    protected void playWithKinds(String url, ArticleItem articleItem) {
        if (isAutoPlay) {
            startPlay(url, articleItem);
        } else {
            audio_play.setImageResource(R.drawable.audio_playbtn);
        }
        audio_play.setClickable(true);
        updateToggleDrawable();
    }

    //TODO
    protected void startPlay(String url, ArticleItem articleItem) {

        getDeatils = true;
        isPlay = true;
        isComplete = false;
        Intent intent = new Intent();
        intent.putExtra(AudioConst.Action, AudioConst.PlayVod);
        //		String url="http://wow2.cnr.cn/live28/jjzs/playlist.m3u8";
        intent.putExtra("url", url);
        intent.putExtra("data", articleItem);
        intent.setClass(getContext(), AudioVodPlayService.class);
        startService(intent);

    }

    protected void togglePauseAudio() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), AudioVodPlayService.class);
        if (isPlay) {
            intent.putExtra(AudioConst.Action, AudioConst.Pause);
            isPlay = false;
        } else {
            isPlay = true;
            if (!isComplete)
                intent.putExtra(AudioConst.Action, AudioConst.OnResume);
            else {
                sendPlayCMD();
            }
        }
        startService(intent);
        updateToggleDrawable();
    }

    protected void sendPlayCMD() {
        try {
            JSONObject video = new JSONObject(articleItem.getAudio());
            JSONArray tsAddress = video.optJSONArray("PC");
            streamLabelList.clear();
            lineMap.clear();
            for (int i = 0; i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                String title = line.optString("title");
                url = line.optString("url");
                lineMap.put(title, url);
                if (lineIndex == -1) {
                    if (i == tsAddress.length() - 1) {
                        lineIndex = i;
                        playWithKinds(url, articleItem);
                    }
                } else {
                    if (i == lineIndex) {
                        lineIndex = i;
                        playWithKinds(url, articleItem);
                        //TODO
                        //streamLineBtn.setText(title);
                    }
                }
                streamLabelList.add(title);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(getContext(), R.string.noraml_newserror);
        }
    }

    protected void updateToggleDrawable() {
        Drawable toggleDrawable;
        if (isPlay) {
            toggleDrawable = getResources().getDrawable(R.drawable.audio_pausbtn);
        } else {
            toggleDrawable = getResources().getDrawable(R.drawable.audio_playbtn);
        }
        audio_play.normalImg = audio_play.pressImg = toggleDrawable;
        audio_play.updateEffDrawable();
    }


    public ComponentName startService(Intent service) {
        return getContext().startService(service);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.audio_p) {
            if (isFirst && !isAutoPlay) {
                isAutoPlay = true;
                isFirst = false;
                isComplete = true;
                startPlay(url, articleItem);
            } else {
                togglePauseAudio();
            }
        }
    }

    @Override
    public void updateCurrentTime(Intent intent) {

        long time = intent.getLongExtra("time", 0);
        long total = intent.getLongExtra("total", 0);
        int cur = (int) (time / 1000);
        int tot = (int) (total / 1000);
        String currentTime = Tools.convertTimeFormat(cur);
        String duration = Tools.convertTimeFormat(tot);
        play_progress.setText(currentTime);

    }

    @Override
    public void audioComplete(Intent intent) {
        isPlay = false;
        isComplete = true;
        updateToggleDrawable();
    }

    @Override
    public void seekComplete() {

    }

    @Override
    public void togglePauseAudio(Intent intent) {

    }

    @Override
    public void onPause() {
        togglePauseAudio();
        super.onPause();
    }
}